﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Super.Collection.Visual.Datas
{
	public class DataOperaion
	{
		public static LotteryDraw Save(LotteryDraw draw)
		{
			var db = new SuperCollectionEntities();
			var oldDraw = db.LotteryDraw.Where(p => p.Issuer == draw.Issuer && p.Game == draw.Game && p.IssueNumber == draw.IssueNumber && p.CollectionSource == draw.CollectionSource).SingleOrDefault();
			if (oldDraw != null)
			{
				Boolean changed = false;
				if (oldDraw.Bets != draw.Bets)
				{
					oldDraw.Bets = draw.Bets;
					changed = true;
				}
				if (oldDraw.BonusNumbers != draw.BonusNumbers)
				{
					oldDraw.BonusNumbers = draw.BonusNumbers;
					changed = true;
				}
				if (oldDraw.CumulativeAmount != draw.CumulativeAmount)
				{
					oldDraw.CumulativeAmount = draw.CumulativeAmount;
					changed = true;
				}
				if (oldDraw.Numbers != draw.Numbers)
				{
					oldDraw.Numbers = draw.Numbers;
					changed = true;
				}

				if (!changed) return oldDraw;
			}
			else
			{
				oldDraw = db.LotteryDraw.Add(draw);
			}
			db.SaveChanges();
			return oldDraw;
		}

		public static void Save(LotteryDraw draw, List<WinningDetail> details)
		{
			draw = Save(draw);
			var db = new SuperCollectionEntities();
			var oldDetails = db.WinningDetail.Where(p => p.DrawId == draw.Id).ToList();
			oldDetails = oldDetails.OrderBy(p => p.Serial).ToList();
			if (oldDetails.Count == details.Count)
			{
				for (Int32 i = 0; i < oldDetails.Count; i++)
				{
					var oldDetail = oldDetails[i];
					var detail = details[i];
					Boolean changed = false;
					if (oldDetail.Award != detail.Award)
					{
						oldDetail.Award = detail.Award;
						changed = true;
					}
					if (oldDetail.MoneyPerWinner != detail.MoneyPerWinner)
					{
						oldDetail.MoneyPerWinner = detail.MoneyPerWinner;
						changed = true;
					}
					if (oldDetail.NumberOfWinners != detail.NumberOfWinners)
					{
						oldDetail.NumberOfWinners = detail.NumberOfWinners;
						changed = true;
					}
					if (oldDetail.Serial != detail.Serial)
					{
						oldDetail.Serial = detail.Serial;
						changed = true;
					}

					if (!changed) continue;
				}
			}
			else
			{
				foreach (var oldDetail in oldDetails)
				{
					db.WinningDetail.Remove(oldDetail);
				}
				foreach (var detail in details)
				{
					detail.DrawId = draw.Id;
					db.WinningDetail.Add(detail);
				}
			}
			db.SaveChanges();
		}
	}
}
